package com.link.base.base.consumer.controller;

import com.link.base.user.model.CoreUser;
import com.link.base.base.accnt.model.Account;
import com.link.base.base.consumer.exception.RepeatOrderNoException;
import com.link.base.base.consumer.model.ImpOrder;
import com.link.base.base.consumer.service.ImpData2AccntService;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.UserUtil;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * created 20180423
 *
 * @author Li Yang
 * 将导入订单转换为消费者（客户）以及对应的订单
 * 目前包括天猫订单以及京东订单
 */
@Controller
@RequestMapping("/link/ord2accnt")
public class ImpData2AccntController extends BasicController<Account> {

    @Resource
    private ImpData2AccntService impData2AccntService;


    /**
     * 导入电商订单入口
     * @author Li Yang
     * @param orderSource
     * @param entity
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/import/{orderSource}")
    @ResponseBody
    public Map<String, Object> importData(@PathVariable String orderSource, @JsonParam Account entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("import").withMessage("导入订单并生成消费者（客户）...").flush();
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.generateAccntFromOrder(orderSource, qps, request);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (RepeatOrderNoException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", "导入数据出现异常！");
        }
        return result;
    }

    /**
     * 查询导入的订单头
     * @author
     * @param entity
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryImportOrderHeadPage")
    @ResponseBody
    public Map<String, Object> queryImportOrderHeadPage(@JsonParam ImpOrder entity, @JsonParam QueryParams qps, HttpSession session,
                                                        HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryImportOrderHeadPage").withMessage("导入订单并生成消费者（客户）...").flush();
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            qps.preDealSecurity(request);
            ImpOrder record = (ImpOrder) BasicModel.transformClass(entity, qps);
            CoreUser user = UserUtil.getUser();
            if (null == user.getId()) {
                record.setCreatedBy(0L);
            } else {
                record.setCreatedBy(user.getId());
            }
            List<ImpOrder> list = impData2AccntService.queryImportOrderHeadPage(record);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) record, list.size()));
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 查询导入的订单行
     * @author Li Yang
     * @param entity
     * @param qps
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/queryImportOrderItemPage")
    @ResponseBody
    public Map<String, Object> queryImportOrderItemPage( @JsonParam ImpOrder entity, @JsonParam QueryParams qps, HttpSession session,
                                                        HttpServletRequest request, HttpServletResponse response) {
        LCLogger.info().withMessageKey("queryImportOrderItemPage").withMessage("导入订单并生成消费者（客户）...").flush();
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            qps.preDealSecurity(request);
            ImpOrder record = (ImpOrder) BasicModel.transformClass(entity, qps);
            if (null == record.getHeadId()) {
                record.setHeadId(0L);
            }
            List<ImpOrder> list = impData2AccntService.queryImportOrderItemPage(record);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount((BasicModel) record, list.size()));
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新订单头临时表
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/tempOrderHeadUpdate")
    @ResponseBody
    public Map<String, Object> tempOrderHeadUpdate( @JsonParam ImpOrder entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.tempOrderHeadUpdate(entity);
            entity.setPageFlag(false);
            ImpOrder newEntry = impData2AccntService.queryImportOrderHeadPage(entity).get(0);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新导入的订单行临时表
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/tempOrderItemUpdate")
    @ResponseBody
    public Map<String, Object> tempOrderItemUpdate( @JsonParam ImpOrder entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.tempOrderItemUpdate(entity);
            //用一个扩展字段做查询字段，避免后面出现歧义（这里导入的头行是用的一个model）
            entity.setAttr0425(entity.getId());

            entity.setPageFlag(false);
            ImpOrder newEntry = impData2AccntService.queryImportOrderItemPage(entity).get(0);
            result.put("newRow", newEntry);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 删除订单临时表头表
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/deleteTempOrder")
    @ResponseBody
    public Map<String, Object> deleteTempOrder(@JsonParam ImpOrder entity, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.deleteTempOrder(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 删除订单临时表行表
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/deleteTempOrderItem")
    @ResponseBody
    public Map<String, Object> deleteTempOrderItem(@JsonParam ImpOrder entity, HttpSession session,
                                                   HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.deleteTempOrderItem(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 校验导入的订单
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/checkOrder")
    @ResponseBody
    public Map<String, Object> checkOrder(@JsonParam ImpOrder entity, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.checkOrder();
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 根据导入订单生成消费者
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/generateConsumer")
    @ResponseBody
    public Map<String, Object> generateConsumer(@JsonParam ImpOrder entity, HttpSession session,
                                                HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            impData2AccntService.generateConsumer();
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 取消已导入的临时订单
     * @author Li Yang
     * @param entity
     * @param session
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/cancelImport")
    @ResponseBody
    public Map<String, Object> cancelImport(@JsonParam ImpOrder entity, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(16);
        try {
            CoreUser user = UserUtil.getUser();
            entity.setLoginCorpId(user.getCorpid());
            entity.setCreatedBy(user.getId());
            impData2AccntService.cancelImport(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
